package top.lingkang.finalvalidated.utils;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * @author lingkang
 * created by 2025-10-13
 */
class GetterUtils {
    /**
     * 查找 getter 方法
     */
    public static Method findGetterMethod(Field field) {
        if (field == null) return null;
        String[] possibleMethods = {
                "get" + capitalize(field.getName()),  // getXxx
                "is" + capitalize(field.getName())    // isXxx
        };

        for (String methodName : possibleMethods) {
            try {
                return field.getDeclaringClass().getMethod(methodName);
            } catch (NoSuchMethodException e) {
                // 继续尝试下一个可能的方法名
            }
        }

        throw new RuntimeException(
                "在类 " + field.getDeclaringClass().getName() + " 中未找到属性 '" + field.getName() + "' 的 getter 方法");
    }

    public static String getTagByAnnotation(Annotation annotation) {
        if (annotation == null) return null;
        try {
            Method method = annotation.getClass().getDeclaredMethod("tag");
            return (String) method.invoke(annotation);
        } catch (Exception e) {
        }
        return null;
    }

    private static String capitalize(String str) {
        if (str == null || str.isEmpty()) return str;
        return Character.toUpperCase(str.charAt(0)) + str.substring(1);
    }
}
